package com.sys.basics.config.socketio;

import cn.hutool.core.util.NumberUtil;
import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.protocol.Packet;
import com.corundumstudio.socketio.store.pubsub.DispatchMessage;
import com.corundumstudio.socketio.store.pubsub.PubSubListener;
import com.corundumstudio.socketio.store.pubsub.PubSubStore;
import com.corundumstudio.socketio.store.pubsub.PubSubType;
import com.sys.basics.config.socketio.nameSpaceListener.AbstractEventLintener;
import com.sys.basics.config.socketio.nameSpaceListener.InterfaceEventListener;
import com.sys.basics.config.socketio.nameSpaceListener.NameSpaceEventListenerMgr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;


@Slf4j
@Component
@ConditionalOnProperty(prefix = "socketio", name = "enable", havingValue = "true")
public class ApplicationStartSocketIoListener implements ApplicationListener<ApplicationStartedEvent> {

    @Autowired
    PubSubStore socketIoPubSubStore;

    @Autowired
    SocketIOServer nettySocketIOServer;

    @Autowired
    NameSpaceEventListenerMgr nameSpaceEventListenerMgr;

    @Autowired
    AbstractEventLintener abstractEventLintener;

    /**
     * @author: ares
     * @date: 2021/11/8 11:06
     * @description: 取消默认订阅的dispatch,重新自定义
     */
    private void subscribeCustomDispatch(){
        PubSubStore socketIoPubSubStore = nettySocketIOServer.getConfiguration().getStoreFactory().pubSubStore();
        socketIoPubSubStore.unsubscribe(PubSubType.DISPATCH);
        socketIoPubSubStore.subscribe(PubSubType.DISPATCH, new PubSubListener<DispatchMessage>() {
            @Override
            public void onMessage(DispatchMessage msg) {
                abstractEventLintener.onSubscribeMessage(msg);
                log.info(">>>收到订阅的数据<<< \n {}", (Object) msg.getPacket().getData());
            }
        }, DispatchMessage.class);
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info(">>>SocketIoServer启动中...<<<");
        HashMap<String, InterfaceEventListener> nameSpaceListener = nameSpaceEventListenerMgr.getNameSpaceListener();
        nameSpaceListener.forEach((nsp, listener)->{
            nettySocketIOServer.addNamespace(nsp).addListeners(listener);
        });
        nettySocketIOServer.start();
        subscribeCustomDispatch();
        log.info(">>>SocketIoServer启动成功<<<");
    }
}
